function calculateBazi(date, time) {
    const dateObj = new Date(date);
    const year = dateObj.getFullYear(),
        month = dateObj.getMonth() + 1,
        day = dateObj.getDate(),
        hour = parseInt(time.split(":")[0]);

    const heavenlyStems = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"];
    const earthlyBranches = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];

    // 年柱计算（简化立春判断，实际需精确节气）
    const springFestival = new Date(year, 1, 4); // 假设立春在2月4日
    const yearOffset = dateObj < springFestival ? year - 1 : year;
    const yearStem = heavenlyStems[(yearOffset - 4) % 10];
    const yearBranch = earthlyBranches[(yearOffset - 4) % 12];

    // 月柱计算（简化节气判断，公历月份映射）
    const monthBranch = earthlyBranches[(month - 1) % 12]; // 1月=寅（索引2），2月=卯（索引3）...
    const monthStemIndex = ((yearOffset % 10) * 2 + month) % 10;
    const monthStem = heavenlyStems[monthStemIndex];

    // 日柱计算（基日为1900年1月31日，蔡勒公式简化版）
    const baseDate = new Date(1900, 0, 31);
    const diffDays = Math.floor((dateObj - baseDate) / (24 * 60 * 60 * 1000));
    const dayStem = heavenlyStems[(diffDays + 9) % 10];
    const dayBranch = earthlyBranches[(diffDays + 9) % 12];

    // 时柱计算
    const hourBranchIndex = Math.floor((hour + 1) / 2) % 12;
    const hourBranch = earthlyBranches[hourBranchIndex];
    const dayStemIndex = heavenlyStems.indexOf(dayStem);
    const hourStemIndex = (dayStemIndex * 2 + Math.floor(hour / 2)) % 10;
    const hourStem = heavenlyStems[hourStemIndex];

    // 校验所有柱是否有效
    if (
        !yearStem || !yearBranch ||
        !monthStem || !monthBranch ||
        !dayStem || !dayBranch ||
        !hourStem || !hourBranch
    ) {
        console.error("八字计算中部分干支生成失败");
        return null;
    }

    return {
        year: `${yearStem}${yearBranch}`,
        month: `${monthStem}${monthBranch}`,
        day: `${dayStem}${dayBranch}`,
        hour: `${hourStem}${hourBranch}`,
        dayMaster: dayStem
    };
}

function analyzeBazi(bazi) {
    const elements = {
        "甲": "木", "乙": "木", "丙": "火", "丁": "火",
        "戊": "土", "己": "土", "庚": "金", "辛": "金",
        "壬": "水", "癸": "水"
    };

    const tenGods = {
        "甲": { "甲": "比肩", "乙": "劫财", "丙": "食神", "丁": "伤官", "戊": "偏财", "己": "正财", "庚": "七杀", "辛": "正官", "壬": "偏印", "癸": "正印" },
        "乙": { "甲": "劫财", "乙": "比肩", "丙": "伤官", "丁": "食神", "戊": "正财", "己": "偏财", "庚": "正官", "辛": "七杀", "壬": "正印", "癸": "偏印" },
        "丙": { "甲": "偏印", "乙": "正印", "丙": "比肩", "丁": "劫财", "戊": "食神", "己": "伤官", "庚": "偏财", "辛": "正财", "壬": "七杀", "癸": "正官" },
        "丁": { "甲": "正印", "乙": "偏印", "丙": "劫财", "丁": "比肩", "戊": "伤官", "己": "食神", "庚": "正财", "辛": "偏财", "壬": "正官", "癸": "七杀" },
        "戊": { "甲": "七杀", "乙": "正官", "丙": "偏印", "丁": "正印", "戊": "比肩", "己": "劫财", "庚": "食神", "辛": "伤官", "壬": "偏财", "癸": "正财" },
        "己": { "甲": "正官", "乙": "七杀", "丙": "正印", "丁": "偏印", "戊": "劫财", "己": "比肩", "庚": "伤官", "辛": "食神", "壬": "正财", "癸": "偏财" },
        "庚": { "甲": "偏财", "乙": "正财", "丙": "七杀", "丁": "正官", "戊": "偏印", "己": "正印", "庚": "比肩", "辛": "劫财", "壬": "食神", "癸": "伤官" },
        "辛": { "甲": "正财", "乙": "偏财", "丙": "正官", "丁": "七杀", "戊": "正印", "己": "偏印", "庚": "比肩", "辛": "劫财", "壬": "伤官", "癸": "食神" },
        "壬": { "甲": "食神", "乙": "伤官", "丙": "偏财", "丁": "正财", "戊": "七杀", "己": "正官", "庚": "偏印", "辛": "正印", "壬": "比肩", "癸": "劫财" },
        "癸": { "甲": "伤官", "乙": "食神", "丙": "正财", "丁": "偏财", "戊": "正官", "己": "七杀", "庚": "正印", "辛": "偏印", "壬": "劫财", "癸": "比肩" }
    };

    const elementCounts = { "木": 0, "火": 0, "土": 0, "金": 0, "水": 0 };
    const pillars = [bazi.year, bazi.month, bazi.day, bazi.hour];

    pillars.forEach(pillar => {
        const stem = pillar[0];
        const element = elements[stem];
        if (element) {
            elementCounts[element]++;
        }
    });

    const dayMaster = bazi.dayMaster;
    const godRelations = dayMaster && tenGods[dayMaster]
      ? pillars.map(pillar => tenGods[dayMaster][pillar[0]] || "未知")
        : ["未知", "未知", "未知", "未知"];

    const dayElement = elements[dayMaster];
    const strength = calculateStrength(dayElement, elementCounts);
    const advice = strength === "身强" ? "克泄" : "生扶";

    return [
        { title: "八字排盘", content: `${bazi.year} ${bazi.month} ${bazi.day} ${bazi.hour}` },
        { title: "五行分布", content: Object.entries(elementCounts)
               .map(([elem, count]) => `${elem}${count}`)
               .join(" ") },
        { title: "十神关系", content: godRelations.join(" ") },
        { title: "日主强弱", content: strength },
        { title: "大运建议", content: `当前行${bazi.month}大运，宜${advice}（身强喜克泄，身弱喜生扶）` }
    ];
}

function calculateStrength(dayElement, counts) {
    if (!dayElement) return "未知";
    const supportMap = {
        "木": ["水", "木"],
        "火": ["木", "火"],
        "土": ["火", "土"],
        "金": ["土", "金"],
        "水": ["金", "水"]
    };
    const supportCount = supportMap[dayElement].reduce((acc, elem) => acc + (counts[elem] || 0), 0);
    return supportCount >= 3 ? "身强" : "身弱";
}

function analyzeBaziWithMarriage(bazi, gender) {
    const basicAnalysis = analyzeBazi(bazi);
    const marriageAnalysis = [];

    const spouseStarMap = {
        male: {
            "木": ["土"],
            "火": ["金"],
            "土": ["水"],
            "金": ["木"],
            "水": ["火"]
        },
        female: {
            "木": ["金"],
            "火": ["水"],
            "土": ["木"],
            "金": ["火"],
            "水": ["土"]
        }
    };

    const elements = {
        "甲": "木", "乙": "木", "丙": "火", "丁": "火",
        "戊": "土", "己": "土", "庚": "金", "辛": "金",
        "壬": "水", "癸": "水"
    };

    const dayElement = elements[bazi.dayMaster];
    const spouseStars = spouseStarMap[gender][dayElement];

    const pillars = [bazi.year, bazi.month, bazi.day, bazi.hour];
    const spouseStarCount = pillars.reduce((acc, pillar) => {
        const stem = pillar[0];
        const element = elements[stem];
        if (spouseStars.includes(element)) {
            return acc + 1;
        }
        return acc;
    }, 0);

    let marriageSituation = "";
    if (spouseStarCount === 0) {
        marriageSituation = "姻缘较晚出现，可能需要耐心等待，积极社交拓展人脉。";
    } else if (spouseStarCount === 1) {
        marriageSituation = "正缘出现时间较为适中，在适婚年龄遇到合适对象的概率较大。";
    } else {
        marriageSituation = "感情缘分较为丰富，可能较早遇到合适的人，但需注意感情选择，避免纠葛。";
    }

    marriageAnalysis.push({
        title: "一生姻缘情况",
        content: marriageSituation
    });

    return [...basicAnalysis, ...marriageAnalysis];
}

export { calculateBazi, analyzeBaziWithMarriage };    